<template>
  <div class="container">
    <!-- <Content> -->
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="板块" class="section" prop="sectionId">
        <el-select v-model="form.sectionId" placeholder="请选择" clearable>
          <el-option
            v-for="item in sections"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <WangEditor v-model="form.content" :show-aside="false" height="350px"></WangEditor>
    <el-button type="primary" @click="submit">添加</el-button>

    <!-- </Content> -->
  </div>
</template>

<script setup lang="ts">
import WangEditor from "@/components/WangEditor.vue";
import Content from "@/layout/Content.vue";
import { ref, reactive, watch, getCurrentInstance } from "vue";
import {listSection} from '@/api/section'
import { addBlog } from "@/api/blog";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter()
const form = reactive({
  title: '',
  sectionId: '',
  content: 'aaa',
});

const { proxy } = getCurrentInstance();


const formRef = ref<FormInstance>()


const sections = ref<any>([]);
// const tags = reactive([]);

const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  sectionId: [{ required: true, message: "请选择板块", trigger: "blur" }]
  });


function submit() {
  proxy.$refs.formRef.validate((valid: any) => {
    if (!valid) return ElMessage.warning('请输入必要的信息')
    addBlog(form).then(res => {
      if (res.code !== 200) return ElMessage.error(res.message)
      ElMessage.success(res.message)
      router.push("/home")
    })
  })
}

function getSection() {
  console.log('getSection');

  listSection().then(res => {
    sections.value.push(...res.data)
    console.log(sections);

  })
}

const handleClick = (e: any) => {
  console.log(e.target.value);
};

const handleChange = () => {
  // form.tagsNew = val.filter((item) => typeof item === "string");
  // // form.tags = form.tags.filter(item => typeof item === 'number')
  // console.log(val, form.tagsNew);
};

function handleAddSuccess() {}

watch(
  () => form.content,
  (newVal) => {
    console.log(newVal);
  }
);


getSection()
</script>

<style scoped lang="less">
.container {
  width: 80%;
  margin: 20px auto;
}
</style>
